#include "gfifo.h"

#ifdef GFIFO_DEBUG
#define dbg_print(fmt, ...) printk(fmt, ##__VA_ARGS__)
#else
#define dbg_print(fmt, ...)
#endif

#ifdef USING_PTR_FIFO
DECLARE_KFIFO_PTR(gfifo, char);
#else
DEFINE_KFIFO(gfifo, char, 32);
#endif

//打开设备
static int gfifo_open(struct inode *inode, struct file *file)
{
	return 0;
}

//释放设备，应用层执行最后一次close时执行
static int gfifo_release(struct inode *inode, struct file *file)
{
	return 0;
}

//读设备
static ssize_t gfifo_read(struct file *file, char __user *buf, size_t len, loff_t *pos)
{
	unsigned int copied;

	if(kfifo_is_empty(&gfifo))
	{
		dbg_print("fifo is empty\r\n");
		return -EINVAL;
	}

	//将FIFO中的数据读取到应用层
	if(kfifo_to_user(&gfifo, buf, len, &copied) != 0)
	{
		dbg_print("Bad address\r\n");
		return -EFAULT;
	}
	return copied;
}

//写设备
static ssize_t gfifo_write(struct file *file, const char __user *buf, size_t len, loff_t *pos)
{
	unsigned int copied;

	if(kfifo_is_full(&gfifo))
	{
		dbg_print("fifo is full\r\n");
		return -EINVAL;
	}

	//将应用层的数据写入FIFO
	if(kfifo_from_user(&gfifo, buf, len, &copied) != 0)
	{
		dbg_print("Bad address\r\n");
		return -EFAULT;
	}
	return copied;
}

//设备号
static dev_t dev_id;
//cdev对象
static struct cdev gfifo_cdev;
//操作函数
static struct file_operations gfifo_ops = {
	.owner = THIS_MODULE,
	.write = gfifo_write,
	.read = gfifo_read,
	.open = gfifo_open,
	.release = gfifo_release,
};

static int __init gfifo_init(void)
{
	int err = 0;
	int i;

#ifdef USING_PTR_FIFO
	err = kfifo_alloc(&gfifo, 32, GFP_KERNEL);
	if(err != 0)
	{
		dbg_print("kfifo alloc failed\r\n");
		return err;
	}
#endif

#ifndef USING_ALLOC_DEV_ID
	//合成设备号
	dev_id = MKDEV(GFIFO_MAJOR, GFIFO_MINOR);
	//静态注册字符设备号
	err = register_chrdev_region(dev_id, GFIFO_CNT, GFIFO_NAME);
	if(err != 0)
	{
#ifdef USING_PTR_FIFO
		kfifo_free(&gfifo);
#endif
		dbg_print("register chrdev failed\r\n");
		return err;
	}
#else
	//根据次设备号起始值动态注册字符设备号
	err = alloc_chrdev_region(&dev_id, GFIFO_MINOR, GFIFO_CNT, GFIFO_NAME);
	if(err != 0)
	{
#ifdef USING_PTR_FIFO
		kfifo_free(&gfifo);
#endif
		dbg_print("alloc chrdev failed\r\n");
		return err;
	}
#endif
	//显示主设备号和次设备号
	for(i=0; i<GFIFO_CNT; i++)
	{
		printk("gfifo %d ", i);
		printk("MAJOR %d ", MAJOR(dev_id + i));
		printk("MINOR %d ", MINOR(dev_id + i));
		printk("\r\n");
	}

	//初始化CDEV对象
	cdev_init(&gfifo_cdev, &gfifo_ops);
	gfifo_cdev.owner = THIS_MODULE;

	//向系统添加CDEV对象
	err = cdev_add(&gfifo_cdev, dev_id, GFIFO_CNT);
	if(err != 0)
	{
		unregister_chrdev_region(dev_id, GFIFO_CNT);
#ifdef USING_PTR_FIFO
		kfifo_free(&gfifo);
#endif
		dbg_print("add cdev failed\r\n");
		return err;
	}

	return 0;
}

static  void __exit gfifo_exit(void)
{
	//从系统删除CDEV对象
	cdev_del(&gfifo_cdev);
	//注销字符设备号
	unregister_chrdev_region(dev_id, GFIFO_CNT);
#ifdef USING_PTR_FIFO
	kfifo_free(&gfifo);
#endif
}

module_init(gfifo_init);
module_exit(gfifo_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("LF");
MODULE_DESCRIPTION("global fifo");
MODULE_ALIAS("global_fifo");
